package com.spark.colliery.module.learn

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.annotation.RequiresApi
import android.support.v4.content.LocalBroadcastManager
import android.telephony.TelephonyManager
import android.view.View
import android.webkit.*
import android.widget.LinearLayout
import com.blankj.utilcode.util.LogUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.AgentWebUtils
import com.just.agentweb.PermissionInterceptor
import com.spark.colliery.MainFragment
import com.spark.colliery.R
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.helper.JpushNotifyReceiver
import kotlinx.android.synthetic.main.frag_learn.*

/**
 * 学习
 */
class LearnHomeFragment : BaseFragment() {
    private lateinit var agentWeb: AgentWeb.PreAgentWeb
    private var web: AgentWeb? = null
    private var localNotifyReceiver: LocalNotifyReceiver? = null

    private val reqGallery = 0x6666
    private val permGallery = 0x7777
    private val reqCamera = 0x8888
    private val permCamera = 0x9999

    private var isLocalStorageWrited = false

    companion object {
        fun newInstance(): LearnHomeFragment {
            return LearnHomeFragment()
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_learn
    }

    private var webviewclient = object : WebViewClient() {
        @SuppressLint("MissingPermission")
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            url?.apply {
                LogUtils.e(this)
                tv_title.text = this
                invokeTabUpdate(this != Const.career_web_url)
            }
            if (!isLocalStorageWrited) {
                isLocalStorageWrited = true
                view?.apply {
                    val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                    val deviceID = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        evaluateJavascript("window.localStorage.setItem(\"deviceId\",$deviceID)", null)
                    } else {
                        loadUrl("javacript:(function(){ window.localStorage.setItem(\"deviceId\",$deviceID); })()")
                    }
                }
            }
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            LogUtils.e("iiiiiiii")
            super.onPageStarted(view, url, favicon)
        }
    }

    private val webChromeClient = object : WebChromeClient() {
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
            fileChooserParams?.apply {
                if (isCaptureEnabled) {
                    // camera
                } else {
                    // gallery
                }
            }
            return true
        }

    }

    private val permissionInterceptor = PermissionInterceptor { url, permissions, action ->
        LogUtils.e("[url] $url [permissions] $permissions [action] $action")
        return@PermissionInterceptor false
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        agentWeb = AgentWeb.with(this)
                .setAgentWebParent(ll_web, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT))
                .closeIndicator()
                .setWebChromeClient(webChromeClient)
                .setWebViewClient(webviewclient)
                .setPermissionInterceptor(permissionInterceptor)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
        registerBroadCast()
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        web = agentWeb.go(Const.career_web_url).apply {
            val webView = webCreator.webView.apply {
                isLongClickable = true
                isScrollbarFadingEnabled = false
                isDrawingCacheEnabled = true
            }
            webView.settings.apply {
                javaScriptEnabled = true
                // 缩放
                setSupportZoom(false)
                builtInZoomControls = false
                displayZoomControls = false
                /*
                * normal
                *   - 正常显示咩有变换
                * single-column
                *   - 把所有内容放到 WebView 组件等宽的一列中
                * narrow-columns
                *   - 使所有列的宽度不超过屏幕宽度。默认
                * */
                layoutAlgorithm = when {
                    Build.VERSION.SDK_INT >= 19 -> WebSettings.LayoutAlgorithm.SINGLE_COLUMN
                    else -> WebSettings.LayoutAlgorithm.NORMAL
                }
                // 返回上个页面不刷新，允许本地缓存
                domStorageEnabled = true
                cacheMode = if (AgentWebUtils.checkNetwork(webView.context)) {
                    // 根据 cache-control 获取数据
                    WebSettings.LOAD_DEFAULT
                } else {
                    // 本地缓存优先
                    WebSettings.LOAD_CACHE_ELSE_NETWORK
                }
                // 数据库
                databaseEnabled = true
                // 缓存
                setAppCacheEnabled(true)
                // 缓存路径
                val cacheDir = AgentWebConfig.getCachePath(webView.context)
                setAppCachePath(cacheDir)
                // 缓存大小 8M
                setAppCacheMaxSize(1024 * 1024 * 8)
                // 硬件加速
                when {
                    Build.VERSION.SDK_INT >= 21 -> {
                        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
                    }
                    Build.VERSION.SDK_INT >= 19 -> webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
                    else -> webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
                }
                // 自动加载图片
                loadsImagesAutomatically = true
                // 禁止网络图片
                blockNetworkImage = false
                // 多窗口
                setSupportMultipleWindows(false)
                // 访问文件
                allowFileAccess = true
                // uri 访问文件
                allowFileAccessFromFileURLs = true
                allowContentAccess = true
                allowUniversalAccessFromFileURLs = true
                // js 可以创建窗口
                javaScriptCanOpenWindowsAutomatically = true

                loadWithOverviewMode = true
                useWideViewPort = true
                setNeedInitialFocus(true)
                // 设置 WebView 推荐使用的窗口，使 html 界面自适应屏幕
                useWideViewPort = true
                // 保持表单数据 低于 8.0
                saveFormData = true
                savePassword = true
                defaultTextEncodingName = "utf-8"
                setGeolocationEnabled(true)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        web?.webLifeCycle?.onPause()
    }

    override fun onResume() {
        super.onResume()
        web?.webLifeCycle?.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        web?.webLifeCycle?.onDestroy()
        localNotifyReceiver?.also {
            context?.apply { LocalBroadcastManager.getInstance(this).unregisterReceiver(it) }
        }
    }

    /*override fun onBackPressedSupport(): Boolean {
        invokeTabUpdate(web?.back() == true)
        web?.webCreator?.webView?.apply {
            LogUtils.e("【back】$url")
            if (canGoBack()) {
                goBack()
                return true
            }
        }
        return false
    }*/


    fun canGoback(): Boolean {
        web?.webCreator?.webView?.apply {
            return if (url == Const.career_web_url) false
            else {
                goBack()
                true
            }
        }
        return false
    }

    private fun invokeTabUpdate(gone: Boolean) {
        parentFragment?.let { it as MainFragment }?.updateTabRelation(gone)
    }

    private fun registerBroadCast() {
        localNotifyReceiver = LocalNotifyReceiver()
        val iff = IntentFilter().apply {
            priority = IntentFilter.SYSTEM_HIGH_PRIORITY
            addAction(JpushNotifyReceiver.messageReceivedAction)
        }
        context?.apply {
            LocalBroadcastManager.getInstance(this).registerReceiver(localNotifyReceiver!!, iff)
        }
    }
}

class LocalNotifyReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.apply {
            if (JpushNotifyReceiver.messageReceivedAction == action) {
                val msg = getStringExtra(JpushNotifyReceiver.keyMessage)
                val extraStr = getStringExtra(JpushNotifyReceiver.keyExtras)

                val sb = StringBuilder()
                sb.append("${JpushNotifyReceiver.keyMessage} : $msg\n")
                if (!extraStr.isNullOrBlank()) {
                    sb.append("${JpushNotifyReceiver.keyExtras} : $extraStr\n")
                }
                LogUtils.e("【收到消息】$sb")
            }
        }
    }

}